package cn.dev.mybatis.core;

import cn.dev.mybatis.util.ObjectUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SingleFactory {

    private static final Map<Class<?>, Single> SINGLE_MAP = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public static <T extends Single> T get(Class<T> clazz) {
        if (!SINGLE_MAP.containsKey(clazz)) {
            ObjectUtils.newInstance(clazz);
        }
        return (T) SINGLE_MAP.get(clazz);
    }

    public static class Single implements AutoCloseable {
        public Single() {
            SINGLE_MAP.put(this.getClass(), this);
        }

        @Override
        public void close() {
            SINGLE_MAP.remove(getClass());
        }
    }
}
